package cn.yuanqiao.common.license;

import cn.yuanqiao.common.license.impl.LinuxServerInfos;
import cn.yuanqiao.common.license.impl.WindowsServerInfos;
import cn.yuanqiao.common.license.utils.EncryptAESUtil;
import cn.yuanqiao.common.license.utils.EncryptRSAUtil;
import cn.yuanqiao.common.license.utils.LicenseCheckModel;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.interfaces.RSAPrivateKey;
import java.util.*;

public class YanzhengService {
    private static final Logger log = LoggerFactory.getLogger(YanzhengService.class);

    public static Map<String,String> getYanzhengma(File licFile) {
        Map<String,String> licResult = new HashMap<>();
        licResult.put("code","0");
        String licString = getlicText(licFile);
        if(StringUtils.isEmpty(licString)){
            licResult.put("msg","授权内容为空！");
            licResult.put("code","0");
            return licResult;
        }else {
            log.info("解密前={}",licString);
            JSONObject licJson = JSON.parseObject(licString);
            String prkString = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMnqZQxXEKBakFbl+v3ZnRlERvpYtSsQzYUXFgW2/bvkn3wX4meh65//L7LTg2JH1QNxZmETIvlTUIFzeNZ63Qee8AFxe7gch7LfhViFELqlDRHM92VAJb7DebIYofKHXqZ0FsgalWVSKZmO+cRSyC8507TiV4WTlqsiDUIieQC5AgMBAAECgYBAW5aztTiWc+dX21wB94/MUufwub+dJ3Dqf+5ECgycDAYNjqtabtDkoXj5ndNdyxmJTGbegDQAll6ttDmK24SBbVIZLL6irqt0seeLq9L0gbfZ4NuOQC3QbhRTozTmjLCTufMYxUdcsGWqwtRAWnN2mxpsNqZMdYrQIKm3B+ZHRQJBAOsnHN07uSskbjt052ve5zpjAdZzKpHU4Ale2xO7vIEMzlpfhcAjNM7qO/NlS4J1l1rhwofHCSwKjpqoi5/HsKsCQQDb0PNlyuqL41fjs+t5j/EwTOchy/hb1lWkGO57Pd0UwT1C2L51KS9zDdDTV1pNRGallxUVksOcBV500P3qEvwrAkEA413bG9IuVReRee2sAXHyM1MdqMOMCptAz+6mdusT9ddzApDP2xpvag2zT8DGhOq8IMSe+fep16qRfdqvvhsvpwJBAIH/UtKybH+KVeH995aOwA7WjCJ6pEh7u24uqGsOLP8nQPmVgR182+jpFMTH9kmX2DS54ug9QZ21tyTSrDeQPr0CQAjVS9QFq61VdHxPqK94j6tGNyTkp6qjvkLFLe08DlaWPt+9an28wTlOJEFIebcW3L1+HvXmXZgtdV1yukvOWUc=";
            String jiemiKey = null;
            try {
                RSAPrivateKey prk = EncryptRSAUtil.getPrivateKey(prkString);// 生成验证码私钥
                jiemiKey = EncryptRSAUtil.decryptByPrivateKey(licJson.getString("key"), prk);// 用验证码公钥加密 AES的key
            } catch (Exception e) {
                log.error(e.getMessage(),e);
                licResult.put("msg","解密失败！");
                licResult.put("code","0");
                return licResult;
            }
            String mwsqm = EncryptAESUtil.aesDecrypt(jiemiKey,licJson.getString("shouquanma"));
            log.info("解密后={}",mwsqm);
            LicenseCheckModel sqinfos = JSONObject.parseObject(mwsqm, LicenseCheckModel.class);
            String osName = System.getProperty("os.name").toLowerCase();
            log.info("操作系统类型={}",osName);
            AbstractServerInfos abstractServerInfos = null;
            LicenseCheckModel yzinfos = null ;
            if (osName.startsWith("windows")) {
                abstractServerInfos = new WindowsServerInfos();
                yzinfos = abstractServerInfos.getServerInfos();
            } else if (osName.startsWith("linux")) {
                abstractServerInfos = new LinuxServerInfos();
                yzinfos = abstractServerInfos.getServerInfos();
            }else{//其他服务器类型
                abstractServerInfos = new LinuxServerInfos();
                yzinfos = abstractServerInfos.getServerInfos();
            }
            log.info(yzinfos.toString());
            //----------验证授权信息----------------------------------------
            //验证主板信息
            if(yzinfos.getMainBoardSerial() !=null){
                if(!yzinfos.getMainBoardSerial().equals(sqinfos.getMainBoardSerial())){
                    licResult.put("msg","主板信息验证失败！");
                    licResult.put("code","0");
                    return licResult;
                }
            }
            //验证mac地址
            if(yzinfos.getMacAddress() != null){
                System.out.println("MacAddress>>>>"+yzinfos.getMacAddress());
                if(sqinfos.getMacAddress() == null || sqinfos.getMacAddress().size() == 0){
                    licResult.put("msg","mac地址验证失败！");
                    licResult.put("code","0");
                    return licResult;
                }
                Set<Object> set1 = new HashSet<>(yzinfos.getMacAddress()); //服务器mac
                Set<Object> set2 = new HashSet<>(sqinfos.getMacAddress());  //授权mac
                boolean containsAll = set1.containsAll(set2);  //授权mac是否在服务器mac内
                if(!containsAll){
                    licResult.put("msg","mac地址验证失败！");
                    licResult.put("code","0");
                    return licResult;
                }
            }
            //验证IP
            if(!sqinfos.isIsyongjiu() && yzinfos.getIpAddress() != null){
                if(sqinfos.getIpAddress() == null || sqinfos.getIpAddress().size() == 0){
                    licResult.put("msg","IP验证失败！");
                    licResult.put("code","0");
                    return licResult;
                }
                Set<Object> set1 = new HashSet<>(yzinfos.getIpAddress()); //服务器IP
                Set<Object> set2 = new HashSet<>(sqinfos.getIpAddress());  //授权IP
                boolean containsAll = set1.containsAll(set2);  //授权IP是否在服务器IP内
                if(!containsAll){
                    licResult.put("msg","IP验证失败！");
                    licResult.put("code","0");
                    return licResult;
                }
            }
            if(sqinfos.isIsyongjiu()) {
                licResult.put("msg","永久授权有效！");
                licResult.put("code","1");
                return licResult;
            }else {
                String youxiaoqi = sqinfos.getYouxiaoqi();
                Date date = DateUtils.dateTime( "yyyy-MM-dd",youxiaoqi);
                int days = DateUtils.getDiffDays(new Date() , date);
                if(days<0) {
                    licResult.put("msg","授权过期！");
                    licResult.put("code","2");
                    return licResult;
                }else {
                    licResult.put("code", "1");
                    licResult.put("msg", "有效期剩余"+days+"天");
                    return licResult;
                }
            }
        }
    }

    private static String getlicText(File licFile){
        // 使用try-with-resources语句来自动关闭资源
        try {
            // 读取文件内容到String
            String content = new String(Files.readAllBytes(licFile.toPath()), StandardCharsets.UTF_8);
            return content;
        } catch (IOException e) {
            // 处理可能的IO异常
            log.error(e.getMessage(),e);
        }
        return null;
    }
}
